#include<iostream>
using namespace std;


  struct ListNode {
      int val;
     ListNode *next;
     ListNode() : val(0), next(nullptr) {}
     ListNode(int x) : val(x), next(nullptr) {}
     ListNode(int x, ListNode *next) : val(x), next(next) {}
 };
 
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {

        ListNode* newhead = new ListNode(-1);
        ListNode* prev = newhead;
        //newhead->next=nullptr;
        ListNode* cur = head, * temp = head;
        int n = 0;
        while (cur)
        {
            cur = cur->next;
            n++;
        }
        n = n / k;
        cur = head;
        while (n--)
        {
            int j = k;
            while (j--)
            {
                ListNode* next = cur->next;
                cur->next = prev->next;
                prev->next = cur;
                cur = next;
            }
            prev = temp;
            temp = cur;
            //cur->next = prev->next;
            prev->next = cur;
            //prev = cur;
            

        }
        if (cur) prev->next = cur;
        cur = newhead->next;
        delete newhead;
        return cur;


    }
};

int main()
{
    //1,2,3,4,5  k=2
    ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
    Solution s;
    s.reverseKGroup(head, 2);
    return 0;
}